const { extend, each } = require("jquery");

define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'selectpage'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'project/index' + location.search,
                    add_url: 'project/add',
                    edit_url: 'project/edit',
                    del_url: 'project/del',
                    multi_url: 'project/multi',
                    import_url: 'project/import',
                    table: 'project',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                pageSize: 10,
                pageList: [10, 25, 50, 100, "All"],
                columns: [
                    [
                        { checkbox: true },
                        { field: 'code', title: __('Code'), operate: 'LIKE' },
                        { field: 'name', title: __('Name'), operate: 'LIKE' },
                        { field: 'money', title: __('Money'), operate: 'BETWEEN' },
                        { field: 'type', title: __('Type'), operate: 'LIKE', searchList: type_data },
                        { field: 'p_area', title: "项目区域", formatter: function (e1, e) { return e.province + '-' + e.city + '-' + e.area; }, operate: 'LIKE', searchList: function (column) { return Template('sourcetpl', {}); } },
                        { field: 'word_unit', title: __('Word_unit'), operate: 'LIKE' },
                        { field: 'num', title: "需求人数", operate: 'LIKE' },
                        { field: 'y_num', title: "已抽取人数", operate: 'LIKE' },
                        { field: 'agree_num', title: "已同意人数", operate: 'LIKE' },
                        { field: 'status', title: "项目状态", searchList: { "1": "等待抽取", "2": "抽取中", "3": "已完成" }, formatter: Table.api.formatter.label },
                        { field: 'open_time', title: __('Open_time'), operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'createtime', title: "创建日期", operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        { field: 'last_draw_time', title: "最新补抽日期", operate: 'RANGE', addclass: 'datetimerange', autocomplete: false, formatter: Table.api.formatter.datetime },
                        {
                            field: 'operate',
                            width: "150px",
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    title: "查看",
                                    text: "查看",
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    // icon: 'fa fa-list',
                                    url: 'project/detail',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), { title: "回传数据" });
                                    }
                                },
                                {
                                    name: 'edit',
                                    text: '编辑',
                                    icon: 'fa fa-pencil',
                                    title: __('Edit'),
                                    extend: 'data-toggle="tooltip"',
                                    classname: 'btn btn-xs btn-success btn-editone',
                                    visible: function (row) {
                                        // 编辑按钮 动态是否显示
                                        if (row.status == 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    }
                                },
                                {
                                    name: 'cq_expert',
                                    title: "抽取专家",
                                    text: "抽取专家",
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    // icon: 'fa fa-list',
                                    extend: "data-area='[\"80%\",\"80%\"]'",
                                    url: 'project/extract',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), { title: "回传数据" });
                                    },
                                    visible: function (row) {
                                        if (row.status == 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                                {
                                    name: 'expert_bc',
                                    title: "补抽",
                                    text: "补抽",
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    // icon: 'fa fa-list',
                                    extend: "data-area='[\"80%\",\"80%\"]'",
                                    url: 'project/expert_bc',
                                    callback: function (data) {
                                    },
                                    visible: function (row) {
                                        if (row.is_show_bc == 2 && row.status == 2) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                                {
                                    name: 'cq_etxper_jl',
                                    title: "抽取记录",
                                    text: "抽取记录",
                                    extend: "data-area='[\"70%\",\"70%\"]'",
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'projectexpert/index?id={row.id}',  // 携带参数
                                    callback: function (data) {
                                        // Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        if (row.status != 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                                {
                                    name: 'uploadexpert',
                                    title: "上传专家",
                                    text: "上传专家",
                                    extend: "data-area='[\"70%\",\"70%\"]'",
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'expert/index',  // 携带参数
                                    callback: function (data) {
                                        if (data.result) {
                                            $('.btn-refresh').trigger("click")
                                        }
                                        // $.ajax({
                                        //     type: "POST",
                                        //     url: 'project/upload_expert',
                                        //     dataType: 'json',
                                        //     data: {ids: data.ids_arr,pid:data.project_id},
                                        //     success: function(response) {  
                                        //         if (response.code == 1){
                                        //             Toastr.success("上传成功");
                                        //         } else {
                                        //             Toastr.error(response.msg);
                                        //             return false;
                                        //         }

                                        //     },
                                        //     error: function(xhr, status, error) { 
                                        //     }
                                        // });  
                                    },
                                    visible: function (row) {
                                        if (row.status == 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    }
                                },
                                {
                                    name: 'print_list_1',
                                    title: "打印名单1",
                                    text: "打印名单1",
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    // icon: 'fa fa-magic',
                                    confirm: '确认打印专家名单吗？',
                                    url: 'projectexpert/print1?id={row.id}',
                                    success: function (data, ret) {
                                        window.location.href = data;
                                        // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        // console.log(data, ret);
                                        // Layer.alert('打印失败');
                                        Toastr.error('打印失败');
                                        return false;
                                    },
                                    visible: function (row) {
                                        if (row.status != 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                                {
                                    name: 'print_list',
                                    title: "打印名单",
                                    text: "打印名单",
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    // icon: 'fa fa-magic',
                                    confirm: '确认打印专家名单吗？',
                                    url: 'projectexpert/print?id={row.id}',
                                    success: function (data, ret) {
                                        window.location.href = data;
                                        // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        // console.log(data, ret);
                                        // Layer.alert('打印失败');
                                        Toastr.error(ret.msg);
                                        return false;
                                    },
                                    visible: function (row) {
                                        if (row.status != 1) {
                                            return true
                                        } else {
                                            return false
                                        }
                                    },
                                },
                            ],
                            formatter: Table.api.formatter.operate
                        },
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'project/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id') },
                        { field: 'name', title: __('Name'), align: 'left' },
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'project/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'project/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        expert_bc: function () {
            // document.getElementsByClassName("sp_hidden").addEventListener('input', function(event) {
            //    debugger
            // });
            // let elements = document.getElementsByClassName("majormajor"); 
            // var e_len =elements?elements.length:0;
            // var e_len_1 = 0;
            var expert_result_ids = [];
            var loding_index = null;

            $(document).ready(function () {
                // $(".majormajor").selectPage({
                //     eAjaxSuccess: function (data) {

                //         data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
                //         data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
                //         return data;
                //     }
                // });

                // 添加行
                $('#add-row').click(function () {
                    var newRow = $('#row-template').html();
                    $('#dynamic-table tbody').append(newRow);
                    Form.events.selectpage();
                    Form.events.cxselect($("#dynamic-table tbody tr:last-child"))

                });

                // 删除行
                $(document).on('click', '.remove-row', function () {
                    var rowIndex = $(this).closest('tr').index();
                    $(this).closest('tr').remove();
                    expert_result_ids = expert_result_ids.splice(rowIndex, 1)
                    updateTr(rowIndex)
                });


                async function updateTr(rowIIndex = 0) {
                    // console.log('rowIIndex', rowIIndex)
                    loding_index = layer.msg('数据加载中...', { icon: 16, shade: 0.3, time: 0 });
                    var rows = $('#dynamic-table tbody tr');
                    const rowsArray = Array.from(rows);

                    for (let i = 0; i < rowsArray.length; i++) {
                        var rowIndex1 = $(rowsArray[i]).closest('tr').index();
                        if (rowIIndex <= rowsArray.length - 1) {
                            expert_result_ids[rowIIndex] = '';
                        }
                        var rowData = {};
                        $(rowsArray[i]).find('td').each(function (index, td) {
                            if ($(td).find('select').attr('k_field') == 'pb_province') {
                                $(td).find('select').each(function (indexx, tdd) {
                                    rowData[$(tdd).attr('k_field')] = $(tdd).val();
                                });
                            } else {
                                rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                            }
                        });
                        // console.log(expert_result_ids)
                        var bc_id = $("#ids").val();
                        var bc_params = { rowData: rowData, ids: bc_id, expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex1 }
                        try {
                            // 每次循环等待请求完成
                            const response = await $.ajax({
                                url: 'project/signeExpert',
                                dataType: 'json',
                                method: 'POST',
                                data: bc_params // 示例：获取行数据
                            });
                            Layer.close(loding_index);
                            if (response.code == 1) {
                                if (response.data) {
                                    let count = response.data.length;
                                    $(rowsArray[i]).find('.fuhe_num').val(count);
                                    $(rowsArray[i]).find('.cq_num').val(0);
                                    $(rowsArray[i]).find('.cq_num').attr('max', count);
                                    $(rowsArray[i]).find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                                    $(rowsArray[i]).find('.expertids').val(response.data.join(','));
                                    expert_result_ids[rowIndex1] = response.data.join(',');
                                }
                            } else {
                            }
                        } catch (error) {
                            Layer.close(loding_index);
                            console.error('请求失败:', error);
                        }
                    }


                    // rows.each(function (index, row) {
                    //     var rowIndex1 = $(row).closest('tr').index();
                    //     var rowData = {};
                    //     $(row).find('td').each(function (index, td) {
                    //         if ($(td).find('select').attr('k_field') == 'pb_province') {
                    //             $(td).find('select').each(function (indexx, tdd) {
                    //                 rowData[$(tdd).attr('k_field')] = $(tdd).val();
                    //             });
                    //         } else {
                    //             rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                    //         }
                    //     });

                    //     var bc_id = $("#ids").val();
                    //     var bc_params = { rowData: rowData, ids: bc_id, expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex1 }

                    //     $.ajax({
                    //         type: "POST",
                    //         url: 'project/signeExpert',
                    //         dataType: 'json',
                    //         data: bc_params,
                    //         // async: true,
                    //         success: function (response) {
                    //             Layer.close(loding_index);
                    //             if (response.code == 1) {
                    //                 if (response.data) {
                    //                     let count = response.data.length;
                    //                     $(row).find('.fuhe_num').val(count);
                    //                     $(row).find('.cq_num').val(0);
                    //                     $(row).find('.cq_num').attr('max', count);
                    //                     $(row).find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                    //                     $(row).find('.expertids').val(response.data.join(','));
                    //                     expert_result_ids[rowIndex1] = response.data.join(','); 
                    //                 }
                    //             } else {
                    //             }
                    //         },
                    //         error: function (xhr, status, error) {
                    //             Layer.close(loding_index);
                    //         }
                    //     });
                    // })
                }

                $('#dynamic-table').on('change', 'select,input[name="item[major][]"]', function () {

                    // loding_index = layer.msg('数据加载中...', { icon: 16, shade: 0.3, time: 0 }); 
                    var rowIndex = $(this).closest('tr').index();
                    updateTr(rowIndex)
                    // var rowData = {}; // 初始化行数据对象 
                    // row.find('td').each(function (index, td) {
                    //     if ($(td).find('select').attr('k_field') == 'pb_province') {
                    //         $(td).find('select').each(function (indexx, tdd) {
                    //             rowData[$(tdd).attr('k_field')] = $(tdd).val();
                    //         });
                    //     } else {
                    //         rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                    //     }
                    // });
                    // var bc_id = $("#ids").val();
                    // var bc_params = { rowData: rowData, ids: bc_id, expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex }
                    // $.ajax({
                    //     type: "POST",
                    //     url: 'project/signeExpert',
                    //     dataType: 'json',
                    //     data: bc_params,
                    //     success: function (response) {
                    //         Layer.close(loding_index);
                    //         if (response.code == 1) {
                    //             if (response.data) {
                    //                 let count = response.data.length;
                    //                 row.find('.fuhe_num').val(count);
                    //                 row.find('.cq_num').val(0);
                    //                 row.find('.cq_num').attr('max', count);
                    //                 row.find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                    //                 row.find('.expertids').val(response.data.join(','));
                    //                 expert_result_ids[rowIndex] = response.data.join(',')
                    //             }
                    //         } else {
                    //         }
                    //     },
                    //     error: function (xhr, status, error) {
                    //         Layer.close(loding_index);
                    //     }
                    // });
                });
            });
            Controller.api.bindevent();
        },
        extract: function () {
            $(document).ready(function () {

                var expert_result_ids = [];
                var loding_index = null;

                // 添加行
                $('#add-row').click(function () {
                    var newRow = $('#row-template').html();
                    $('#dynamic-table tbody').append(newRow);
                    Form.events.selectpage();
                    Form.events.cxselect($("#dynamic-table tbody tr:last-child"))

                });

                async function updateTr(rowIIndex = 0) {
                    // console.log('rowIIndex', rowIIndex)
                    loding_index = layer.msg('数据加载中...', { icon: 16, shade: 0.3, time: 0 });
                    var rows = $('#dynamic-table tbody tr');
                    const rowsArray = Array.from(rows);

                    for (let i = 0; i < rowsArray.length; i++) {
                        var rowIndex1 = $(rowsArray[i]).closest('tr').index();
                        if (rowIIndex <= rowsArray.length - 1) {
                            expert_result_ids[rowIIndex] = '';
                        }
                        var rowData = {};
                        $(rowsArray[i]).find('td').each(function (index, td) {
                            if ($(td).find('select').attr('k_field') == 'pb_province') {
                                $(td).find('select').each(function (indexx, tdd) {
                                    rowData[$(tdd).attr('k_field')] = $(tdd).val();
                                });
                            } else {
                                rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                            }
                        });
                        var bc_id = $("#ids").val();
                        var bc_params = { rowData: rowData, ids: bc_id, expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex1 }
                        try {
                            // 每次循环等待请求完成
                            const response = await $.ajax({
                                url: 'project/signeExpert',
                                dataType: 'json',
                                method: 'POST',
                                data: bc_params // 示例：获取行数据
                            });
                            Layer.close(loding_index);
                            if (response.code == 1) {
                                if (response.data) {
                                    let count = response.data.length;
                                    $(rowsArray[i]).find('.fuhe_num').val(count);
                                    $(rowsArray[i]).find('.cq_num').val(0);
                                    $(rowsArray[i]).find('.cq_num').attr('max', count);
                                    $(rowsArray[i]).find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                                    $(rowsArray[i]).find('.expertids').val(response.data.join(','));
                                    expert_result_ids[rowIndex1] = response.data.join(',');
                                }
                            } else {
                            }
                        } catch (error) {
                            Layer.close(loding_index);
                            console.error('请求失败:', error);
                        }
                    }
                }

                // 删除行
                $(document).on('click', '.remove-row', function () {
                    var rowIndex = $(this).closest('tr').index();
                    expert_result_ids.splice(rowIndex, 1)
                    $(this).closest('tr').remove();
                    updateTr(rowIndex)
                    // loding_index = layer.msg('数据加载中...', { icon: 16, shade: 0.3, time: 0 });
                    // var rows = $('#dynamic-table tbody tr');
                    // rows.each(function (index, row) {
                    //     var rowIndex1 = $(row).closest('tr').index();
                    //     var rowData = {};
                    //     $(row).find('td').each(function (index, td) {
                    //         if ($(td).find('select').attr('k_field') == 'pb_province') {
                    //             $(td).find('select').each(function (indexx, tdd) {
                    //                 rowData[$(tdd).attr('k_field')] = $(tdd).val();
                    //             });
                    //         } else {
                    //             rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                    //         }
                    //     });
                    //     var bc_id = $("#ids").val();
                    //     var bc_params = { rowData: rowData, ids: bc_id, expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex1 }
                    //     $.ajax({
                    //         type: "POST",
                    //         url: 'project/signeExpert',
                    //         dataType: 'json',
                    //         data: bc_params,
                    //         success: function (response) {
                    //             Layer.close(loding_index);
                    //             if (response.code == 1) {
                    //                 if (response.data) {
                    //                     let count = response.data.length;
                    //                     $(row).find('.fuhe_num').val(count);
                    //                     $(row).find('.cq_num').val(0);
                    //                     $(row).find('.cq_num').attr('max', count);
                    //                     $(row).find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                    //                     $(row).find('.expertids').val(response.data.join(','));
                    //                     expert_result_ids[rowIndex1] = response.data.join(',')
                    //                 }
                    //             } else {
                    //             }
                    //         },
                    //         error: function (xhr, status, error) {
                    //             Layer.close(loding_index);
                    //         }
                    //     });
                    // })

                });

                $('#dynamic-table').on('change', 'select,input[name="item[major][]"]', function () {
  
                    var rowIndex = $(this).closest('tr').index();
                    updateTr(rowIndex)

                    // var row = $(this).closest('tr'); // 获取当前行  
                    // var rowData = {}; // 初始化行数据对象 
                    // var rowIndex = $(this).closest('tr').index();
                    // row.find('td').each(function (index, td) {
                    //     if ($(td).find('select').attr('k_field') == 'pb_province') {
                    //         $(td).find('select').each(function (indexx, tdd) {
                    //             rowData[$(tdd).attr('k_field')] = $(tdd).val();
                    //         });
                    //     } else {
                    //         rowData[$(td).find('select,input').attr('k_field')] = $(td).find('select,input').val();
                    //     }
                    // });
                    // // var bc_params = { rowData: rowData, ids: '' }
                    // loding_index = layer.msg('数据加载中...', { icon: 16, shade: 0.3, time: 0 });
                    // var bc_params = { rowData: rowData, ids: '', expert_result_ids: JSON.stringify(expert_result_ids), c_index: rowIndex }
                    // $.ajax({
                    //     type: "POST",
                    //     url: 'project/signeExpert',
                    //     dataType: 'json',
                    //     data: bc_params,
                    //     success: function (response) {
                    //         Layer.close(loding_index);
                    //         if (response.code == 1) {
                    //             if (response.data) {
                    //                 let count = response.data.length;
                    //                 row.find('.fuhe_num').val(count);
                    //                 row.find('.cq_num').val(0);
                    //                 row.find('.cq_num').attr('max', count);
                    //                 row.find('.cq_num').attr('oninput', 'if(value>' + count + ')value=' + count + ';if(value<0)value=0');
                    //                 row.find('.expertids').val(response.data.join(','));
                    //                 expert_result_ids[rowIndex] = response.data.join(',')
                    //             }

                    //             // Toastr.success("上传成功");
                    //         } else {
                    //             // Toastr.error(response.msg);
                    //         }

                    //     },
                    //     error: function (xhr, status, error) {
                    //         Layer.close(loding_index);
                    //     }
                    // });
                });
            });

            Controller.api.bindevent();
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});

function removeEmptyProperties(obj) {
    Object.keys(obj).forEach(function (key) {
        if (obj[key] === '' || obj[key] === ' ' || obj[key] === null || obj[key] === undefined) {
            delete obj[key];
        }
    });
}

function aaa(e) {
    $(e).removeAttr('name');
}

var platesData = [];
let isDrawing = false;
var TOTAL_WINNERS = 0
var fixedResults = []

function submitCq() {
    var index = layer.load(1, {
        shade: 0.1, // 遮罩层透明度为0.1
        color: '#fff', // 遮罩层颜色为白色
        title: "ddd"
    });
    var formData = $("#second-form").serialize(); // 序列化表单数据 
    $.ajax({
        type: "POST",
        url: 'project/extract',
        data: formData,
        success: function (response) {
            layer.close(index);
            if (response.code == 1) {
                let result = response.data.cq_rst
                let allExpert = response.data.allExpert
                // 初始化页面
                initGramd(allExpert, result, result.length)

                $("#second-form").css('display', 'none');
                $("#cq_result_form").css('display', "block")
                return false;
            } else {
                Toastr.error(response.msg);
            }

        },
        error: function (xhr, status, error) {
        }
    });


}


function initGramd(plates, fixedResults, num) {
    platesData = plates;
    renderPlates(platesData);
    document.getElementById('startBtn').addEventListener('click', startLottery(fixedResults, num));

}
// 初始化车牌显示
function renderPlates(plates) {
    const container = document.getElementById('plate-container');
    container.innerHTML = '';
    plates.forEach(plate => {
        const card = document.createElement('div');
        card.className = 'plate-card';
        card.innerHTML = `
            <div class="plate-id" style="display:none">${plate.id}</div>
            <div class="plate-number">${plate.name}</div>
        `;
        container.appendChild(card);
    });
}

// 随机洗牌算法
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// 执行洗牌动画
async function animateShuffle(originalData) {
    return new Promise(resolve => {
        const container = document.getElementById('plate-container');
        container.classList.add('shuffling');

        // 创建临时洗牌副本
        let tempData = [...originalData];

        const shuffleInterval = setInterval(() => {
            tempData = shuffleArray(tempData);
            renderPlates(tempData);
        }, 100);

        setTimeout(() => {
            clearInterval(shuffleInterval);
            container.classList.remove('shuffling');
            resolve(tempData);
        }, 3000);
    });
}

// 标记中奖者
function markWinners(winners) {
    document.querySelectorAll('.plate-card').forEach(card => {
        const id = card.querySelector('.plate-id').textContent;
        for (let i = 0; i < winners.length; i++) {
            if (winners[i]['id'] == id) {
                card.classList.add('highlight');
            }
        }
    });
}

// 自动抽奖流程
async function startLottery(fixedResults, TOTAL_WINNERS) {
    if (isDrawing) return;
    isDrawing = true;
    // 初始化数据
    let workingData = [...platesData];

    // 第一阶段：洗牌动画
    const shuffledData = await animateShuffle(workingData);

    // 第二阶段：确定中奖者
    const allWinners = [...fixedResults];
    const remaining = TOTAL_WINNERS - fixedResults.length;

    // 排除已内定中奖者
    const availablePlates = shuffledData.filter(plate =>
        !fixedResults.some(f => f.id === plate.id)
    );

    // 随机抽取剩余名额
    for (let i = 0; i < remaining && availablePlates.length > 0; i++) {
        const index = Math.floor(Math.random() * availablePlates.length);
        allWinners.push(availablePlates.splice(index, 1)[0]);
    }

    // 显示结果
    markWinners(allWinners);
    showResult(allWinners);

    isDrawing = false;
}

// 显示最终结果
function showResult(winners) {
    const idsArray = winners.map(item => item.id);
    document.getElementById("result_ids").value = idsArray.join(',');
    // const resultDiv = document.getElementById('result');
    // resultDiv.innerHTML = `
    //     <h3>🎉 中奖结果（共${winners.length}名）</h3>
    //     ${winners.map(plate => `
    //         <div class="result-item">
    //             <span class="result-id" style="display:none">${plate.id}</span>
    //             <span class="result-name">${plate.name}</span>
    //         </div>
    //     `).join('')}
    // `;
}




// Fieldlist 容器选择器（根据实际结构调整）
var $fieldlist = $('#basictpl');
// 监听所有输入框的实时变化（事件委托）
$fieldlist.on('input', 'input[type="text"], select, textarea', function (e) {
    // 获取当前行的数据
    var $row = $(this).closest('.fieldlist-item'); // 根据实际行容器类名调整
    var key = $row.find('[name="key[]"]').val();   // 键输入框
    var value = $row.find('[name="value[]"]').val(); // 值输入框

    // 输出调试信息
    console.log('行数据变化：', { key: key, value: value });

    // 执行自定义逻辑（如实时校验、计算、提交等）
    validateRow($row);
});

// 示例：自定义行校验逻辑
function validateRow($row) {
    var value = $row.find('[name="value[]"]').val();
    if (value.length < 3) {
        $row.find('.value-input').addClass('is-invalid');
    } else {
        $row.find('.value-input').removeClass('is-invalid');
    }
}

